package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.QuestionReply;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.QuestionMapper;
import cn.wolfcode.trip.base.mapper.QuestionReplyMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IQuestionReplyService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class QuestionReplyServiceImpl implements IQuestionReplyService {
    @Autowired
    private QuestionReplyMapper questionReplyMapper;
    @Autowired
    private QuestionMapper questionMapper;


    @Override
    public void saveOrUpdate(QuestionReply questionReply) {
        if (questionReply.getId() != null) {
            // 回答更新操作
            questionReplyMapper.updateByPrimaryKey(questionReply);
        } else {

            User currentUser = UserContext.getCurrentUser();
            if (currentUser != null) {
                //设置当前用户为回答者
                questionReply.setReplyUser(currentUser);
                //设置回答新增的时间
                questionReply.setReplyTime(new Date());
                //初始化评论数
                questionReply.setCommentCount(0);
                // 回答新增操作
                questionReplyMapper.insert(questionReply);
                //更新回答数数量
                questionMapper.updateAnswerCountByPrimaryKey(questionReply.getQuestionId());
            } else {
                throw new RuntimeException("获取不到回答者的信息!");
            }
        }
    }


    @Override
    public PageInfo<QuestionReply> listById(Long id, QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<QuestionReply> list = questionReplyMapper.selectAll(id);
        return new PageInfo<>(list);
    }

    @Override
    public QuestionReply getReplyById(Long id) {
        return questionReplyMapper.selectByPrimaryKey(id);
    }


}
